import {AddressModel} from "../../../database/models/address";
import {Delivery, DeliveryModel} from "../../../database/models/delivery";
import {GamePrizeModel} from "../../../database/models/gamePrize";
import {PlayerModel} from "../../../database/models/player";
import {ProductModel} from "../../../database/models/Product";
import {InstanceType} from "typegoose"
import moment = require("moment");

export const typeDefs = `

type Delivery{
  _id: String!
  player: Player!
  prizes: [GamePrize]!
  toAddress: Address!
  fee: Float!
  state: String!
  createAt: String!
  outAt: String!
  endAt:String
  carrier: String
  trackingNumber: String
}

`

export const queryDefs = `
  deliveriesByDate(date:String!): [Delivery]!
  deliveriesByState(state:String!): [Delivery]!
  deliveriesByPlayer(playerId:String!): [Delivery]!
`

export const mutationDefs = `
  deliveryToDelivering(_id:String!,carrier:String!,trackNo:String!): Delivery
  deliveryToDelivered(_id:String!): Delivery
`


export const resolvers = {

  Query: {

    async deliveriesByDate(_, {date}) {

      const begin = moment(date).startOf('day')
      const end = moment(date).startOf('day')

      return DeliveryModel.find({createAt: {$gte: begin, $lt: end}})
    },
    async deliveriesByState(_, {state}) {
      return DeliveryModel.find({state}).sort({createAt: -1})
    },
    async deliveriesByPlayer(_, {playerId}) {
      console.log(playerId)
      const x = await DeliveryModel.find({player: playerId}).sort({createAt: -1})
      console.log(x)
      return x
    }
  },
  Mutation: {
    async deliveryToDelivering(_, {_id, carrier, trackNo}) {
      const delivery: InstanceType<Delivery> = await DeliveryModel.findById(_id)

      if (!delivery) {
        throw Error('NO_SUCH_DELIVERY')
      }

      if (delivery.state === "delivering" || delivery.state === "delivered") {
        throw Error('ALREADY_DELIVERED')
      }

      for (const p of delivery.prizes) {
        await GamePrizeModel.findByIdAndUpdate(p, {$set: {state: 'delivering'}})
      }

      delivery.state = "delivering"
      delivery.carrier = carrier
      delivery.trackingNumber = trackNo
      delivery.outAt = new Date()
      await delivery.save()

      return delivery
    },
    async deliveryToDelivered(_, {_id}) {
      const delivery: InstanceType<Delivery> = await DeliveryModel.findById(_id)

      if (!delivery) {
        throw Error('NO_SUCH_DELIVERY')
      }
      delivery.state = "delivered"
      delivery.endAt = new Date()
      await delivery.save()
      return delivery
    }
  }
  ,

  Delivery: {
    async player({player}) {
      const p = await PlayerModel.findById(player)
      if (p) {
        return p
      } else {
        console.log(player)
        return {_id: player}
      }
    }
    ,
    prizes({prizes}) {
      return GamePrizeModel.find({_id: {$in: prizes}})
    }
    ,
    toAddress({toAddress}) {
      return AddressModel.findById(toAddress)
    }
  }
}
